package oen.game.gateway.network;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * <p>描述：暂无描述信息</p>
 *
 * <p>创建时间：2021-11-10 09:35</p>
 * <p>更新时间：暂无</p>
 *
 * @author Kevin.Xu
 * @version 1.0
 */
public class NettyClient {

    private int port;
    private String host;
    private LogLevel level;
    private ChannelInitializer<SocketChannel> channelChannelInitializer;
    private EventLoopGroup bossGroup;
    private Bootstrap bootstrap;
    private Channel channel;

    public NettyClient(String host, int port, LogLevel level, ChannelInitializer<SocketChannel> channelChannelInitializer) {
        this.port = port;
        this.host = host;
        this.level = level;
        this.channelChannelInitializer = channelChannelInitializer;

        this.init();
    }

    private void init() {
        bossGroup = new NioEventLoopGroup();

        bootstrap = new Bootstrap();
        bootstrap.group(bossGroup);

        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new LoggingHandler(level));

        bootstrap.handler(channelChannelInitializer);
    }

    public Channel connect() throws InterruptedException {
        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
        channel = channelFuture.channel();
        return channel;
    }

    public void send(Object msg) {
        if (this.channel != null) {
            this.channel.writeAndFlush(msg);
        }
    }

    public void stop() throws InterruptedException {
        if (channel != null) {
            channel.closeFuture().sync();
        }
        if (bootstrap != null) {
            bossGroup.shutdownGracefully();
        }
    }
}
